package com.stardata.liangshisq.tcslmon.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stardata.liangshisq.tcslmon.entity.*;
import com.stardata.liangshisq.tcslmon.mapper.*;
import com.stardata.liangshisq.tcslmon.service.BizBsService;
import com.stardata.liangshisq.tcslmon.util.CommonConstants;
import com.stardata.liangshisq.tcslmon.util.CommonUtil;
import lombok.AllArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Samson Shu
 * @email shush@stardata.top
 * @date 2020/7/31 14:54
 */
@Service
@AllArgsConstructor
public class BizBsServiceImpl extends ServiceImpl<BizBsMapper, BizBs>
    implements BizBsService{

  private final BizBsMapper bizBsMapper;
  private final BizScMapper bizScMapper;
  private final BizSsMapper bizSsMapper;
  private final KcKscMapper kcKscMapper;
  private final ArchPointMapper archPointMapper;
  private final ArchItemMapper archItemMapper;
  private final ArchItemProductDeptMapper archItemProductDeptMapper;

  @Override
  @DS("canyin")
  public List<OrderVo> getOrderVosByIds(@NotNull List<Long> orderIds,
                                        Integer kitchenFlg,
                                        boolean onlyCurrentShift,
                                        boolean needZeroQtyItems,
                                        boolean onlyKitchenItems) {
    List<OrderVo> result  = new ArrayList<>();

    for (Long orderId : orderIds) {
      BizBs bizBs = bizBsMapper.selectById(orderId);
      if (bizBs == null) continue;

      //如果只需要后厨制作中项目、且业务流水已经结算，则跳过
      if (onlyKitchenItems && bizBs.getState().equals(1)) continue;

      String remark="";
      QueryWrapper<BizSs> bizSsQueryWrapper = new QueryWrapper<>();
      bizSsQueryWrapper.eq("bs_id", orderId);
      List<BizSs> bizSsList = bizSsMapper.selectList(bizSsQueryWrapper);
      if (bizSsList.size()>0) {
        remark = bizSsList.get(0).getSsRemark();
      }

      OrderVo orderVo = new OrderVo();
      orderVo.setId(orderId);
      orderVo.setServerId(bizBs.getCreatorId());
      orderVo.setOrderTime(bizBs.getOpenTime());
      orderVo.setStatus(bizBs.getState());
      orderVo.setRemark(remark);

      //根据桌位ID找到其编码和名称
      ArchPoint archPoint = archPointMapper.selectById(bizBs.getPointId());
      if (archPoint == null) continue; //没有桌位编码的订单，可以忽略
      orderVo.setTableNo(archPoint.getCode());
      orderVo.setTableName(archPoint.getName());

      //为订单查询其订单项并填入
      List<OrderItemVo> items = new ArrayList<>();
      orderVo.setItems(items);

      QueryWrapper<BizSc> wrapper = new QueryWrapper<>();
      wrapper.eq("bs_id", orderId)
              .orderByAsc("sort_order");
      if (!needZeroQtyItems) {
        wrapper.gt("last_qty", 0);
      }
      //支持只查询当前班次的订单
      if (onlyCurrentShift) {
        /*暂不实现只查询当班的菜品，而只支持8小时内菜品查询
        QueryWrapper<ArchShift> wrapper1 = new QueryWrapper<>();
        wrapper1.orderByDesc("start_time");
        List<ArchShift>  shifts = shiftMapper.selectList(wrapper1);
        LocalTime now = LocalTime.now();
        ArchShift curShift = null;
        for (ArchShift shift : shifts) {
          LocalTime shiftStart = shift.getStartTime();
          if (shift.getIsStartShift() && shiftStart.isBefore(now) ) {
            curShift = shift;
            break;
          }
        }
        if ((curShift == null) && (shifts.size()>0)) {
          curShift = shifts.get(0);
        }
        if (curShift != null) {
          wrapper.eq("shift_id", curShift.getId());
        }
        */

        wrapper.apply("EXTRACT(epoch from (now()-create_time)) < 8*3600");
      }
      List<BizSc> bizScs = bizScMapper.selectList(wrapper);
      List<Long> kdsClassIds = KitchenQueryUtil.getKdsClassIds();
      for (BizSc bizSc : bizScs) {
        OrderItemVo itemVo = new OrderItemVo();
        itemVo.setId(bizSc.getId());
        itemVo.setItemId(bizSc.getItemId().toString());
        itemVo.setOrigQty(bizSc.getOrigQty().intValue());
        itemVo.setLastQty(bizSc.getLastQty().intValue());
        if (itemVo.getLastQty() == 0) continue; //如果数量为零，直接跳过

        //填写订单项的菜品名称
        ArchItem archItem = archItemMapper.selectById(bizSc.getItemId());
        if (archItem == null) {
          //临时品项，将id+name作为菜品的id返回
          itemVo.setName(bizSc.getTempItemName());
          itemVo.setItemId(itemVo.getItemId()+bizSc.getTempItemName());
        } else {
          itemVo.setName(archItem.getName());
        }

        //如果只返回后厨制作菜品、且该菜品不是KDS菜品，则跳过
        if (onlyKitchenItems && archItem!=null &&
            !kdsClassIds.contains(archItem.getSmallClassId())) continue;

        //将做法转换为List列表
        itemVo.setLabels(CommonUtil.methodText2List(bizSc.getMethodText()));

        //查询订单菜品制作进度
        QueryWrapper<KcKsc> kcKscWrapper = new QueryWrapper<>();
        kcKscWrapper.eq("bs_id", orderId)
            .eq("item_id", bizSc.getItemId())
            .eq("sc_id", bizSc.getId());
        List<KcKsc> kcKscList = kcKscMapper.selectList(kcKscWrapper);
        if (kcKscList.size() > 0) {
          KcKsc kcKsc = kcKscList.get(0);
          itemVo.setKscId(kcKsc.getId());
          itemVo.setStatus(kcKsc.getKitchenFlg());
          itemVo.setCreateTime(kcKsc.getCreateTime());
          itemVo.setModifyTime(kcKsc.getModifyTime());
          itemVo.setCookTime(kcKsc.getCookFinishTime());
          itemVo.setPrepareTime(kcKsc.getPrepareFinishTime());
          itemVo.setPassonTime(kcKsc.getServeFinishTime());
        } else {
          itemVo.setStatus(CommonConstants.KitchenFlg.PRODUCED);
        }
        if(onlyKitchenItems && kcKscList.size() <1) continue;

        //将该订单菜品加入到订单项列表
        if (kitchenFlg != null) {
          if (itemVo.getStatus().equals(kitchenFlg)) {
            items.add(itemVo);
          }
        } else if (!onlyKitchenItems
            || itemVo.getStatus().equals(CommonConstants.KitchenFlg.TO_PREPARE)
            || itemVo.getStatus().equals(CommonConstants.KitchenFlg.TO_PASSON)
            || itemVo.getStatus().equals(CommonConstants.KitchenFlg.PRODUCED)
            || bizBs.getSettleTime() == null) {
          //如果只需要厨房操作中的菜品，则不加入结果列表
          items.add(itemVo);
        }

      }

      //当只看后厨订单时，只有订单项目不为空的订单，才需要返回
      if (onlyKitchenItems && items.size()<1) continue;
      result.add(orderVo);
    }

    return result;
  }

  @Override
  @DS("canyin")
  public List<SaleDetail> getSaleDetailsByBsIds(@NotNull List<Long> bizBsIds) {
    List<SaleDetail> result  = new ArrayList<>();
    if (bizBsIds.size()<1) return result;

    QueryWrapper<BizBs> bsQueryWrapper = new QueryWrapper<>();
    QueryWrapper<BizSc> scQueryWrapper = new QueryWrapper<>();
    QueryWrapper<ArchItemProductDept> itemProductDeptQueryWrapper = new QueryWrapper<>();


    bsQueryWrapper.in("id", bizBsIds)
        .and(wq->wq.eq("state", 1));
    List<BizBs> bizBsList = bizBsMapper.selectList(bsQueryWrapper);
    for (BizBs bizBs : bizBsList) {
      ArchPoint archPoint = archPointMapper.selectById(bizBs.getPointId());

      scQueryWrapper.clear();
      scQueryWrapper.eq("bs_id", bizBs.getId());
      List<BizSc> bizScList = bizScMapper.selectList(scQueryWrapper);
      for (BizSc bizSc : bizScList) {
        SaleDetail saleDetail = new SaleDetail();

        //营业流水ID、店铺ID
        saleDetail.setBsId(bizBs.getId());
        saleDetail.setShopId(bizBs.getCreateShopId());

        //菜品ID、名称
        saleDetail.setItemId(bizSc.getItemId());
        itemProductDeptQueryWrapper.clear();
        itemProductDeptQueryWrapper.eq("item_id", bizSc.getItemId());
        ArchItemProductDept archItemProductDept = archItemProductDeptMapper.selectOne(itemProductDeptQueryWrapper);

        if (bizSc.getItemType().equals(2)) {
          //临时品项，返回临时品项名称
          saleDetail.setItemName(bizSc.getTempItemName());
        } else {
          ArchItem archItem = archItemMapper.selectById(bizSc.getItemId());
          if(archItem==null){
            continue;
          }
          saleDetail.setItemName(archItem.getName());
        }

        //桌位ID、名称
        if (archPoint != null) {
          saleDetail.setPointId(archPoint.getId());
          saleDetail.setPointName(archPoint.getName());
        }

        //桌位所处区域ID
        if (archPoint != null) {
          saleDetail.setAreaId(archPoint.getAreaId());
        }

        //出品部门id
        if (archItemProductDept != null) {
          saleDetail.setCookDeptId(archItemProductDept.getDeptId());
        }

        //服务员ID
        saleDetail.setWaiterId(bizSc.getWaiterId());

        //数量、单价、金额
        saleDetail.setLastCount(bizSc.getLastQty().longValue());
        saleDetail.setLastPriceFen((long)(bizSc.getLastPrice()*100));
        saleDetail.setLastTotalFen((long)(bizSc.getLastSubtotal()*100));

        //结算时间
        saleDetail.setSettleTime(bizBs.getSettleTime());

        result.add(saleDetail);
      }
    }

    return result;
  }
}
